import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:file_selector/file_selector.dart' as fs;
import 'dart:io' show Platform;
import 'package:path_provider/path_provider.dart';
import 'package:share_plus/share_plus.dart';
import 'package:provider/provider.dart';
import 'package:cached_network_image/cached_network_image.dart';
import '../services/music_player_service.dart';
import '../services/favorites_service.dart';
import '../services/history_service.dart';
import '../services/music_api_service.dart';
import '../services/custom_playlist_service.dart';
import '../models/song.dart';
import '../widgets/mini_player_widget.dart';
import '../widgets/player_sheet_widget.dart';
import 'search_screen.dart';
import 'hot_songs_screen.dart';
import 'favorites_screen.dart';
import 'history_screen.dart';
import 'ranking_screen.dart';
import 'alger_toplist_screen.dart';
import '../utils/ranking_image_generator.dart';
import '../models/music_source.dart';
import '../services/playlist_management_service.dart';
import '../models/playlist.dart';
import 'custom_playlists_screen.dart';
import 'personal_center_screen.dart';
import '../utils/util.dart';
import 'alger_playlist_screen.dart';
import 'alger_artists_screen.dart';
import 'alger_artist_detail_screen.dart';
import 'alger_mv_list_screen.dart';
import 'alger_playlist_detail_screen.dart';
import '../services/alger_api_service.dart';

class HomeScreen extends StatefulWidget {
  const HomeScreen({super.key});

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> with TickerProviderStateMixin {
  final PageController _bannerController = PageController();
  int _currentBannerIndex = 0;
  int _selectedTabIndex = 0;
  late TabController _tabController;
  Timer? _bannerTimer;

  final List<Map<String, dynamic>> _bannerItems = [
    {
      'title': '热门流行',
      'subtitle': '最新流行音乐精选',
      'image': 'assets/images/banner1.svg',
      'color': const Color(0xFF667eea),
    },
    {
      'title': '古典雅韵',
      'subtitle': '经典古典音乐作品',
      'image': 'assets/images/banner2.svg',
      'color': const Color(0xFF2c3e50),
    },
    {
      'title': '摇滚风暴',
      'subtitle': '激情摇滚音乐合集',
      'image': 'assets/images/banner3.svg',
      'color': const Color(0xFFe74c3c),
    },
    {
      'title': '电音节拍',
      'subtitle': '未来电子音乐体验',
      'image': 'assets/images/banner4.svg',
      'color': const Color(0xFF9b59b6),
    },
  ];

  List<Song> _hotSongs = [];
  List<Song> _newSongs = [];
  List<Song> _favoriteSongs = [];
  List<Song> _customPlaylistSongs = [];
  List<Song> _historySongs = [];
  bool _isLoadingHotSongs = true;
  bool _isLoadingNewSongs = true;
  bool _isLoadingFavorites = true;
  bool _isLoadingCustomPlaylist = true;
  bool _isLoadingHistory = true;
  
  // 折叠展开状态
  bool _isHotSongsExpanded = true;
  bool _isNewSongsExpanded = true;
  // 同页收藏与自定义歌单折叠状态
  bool _isFavoritesExpanded = true;
  bool _isCustomPlaylistsExpanded = true;
  // 多歌单数据与每个歌单的折叠状态
  List<Playlist> _playlists = [];
  bool _isLoadingPlaylists = true;
  final Map<String, bool> _playlistExpanded = {};

  // 经典：两个分类歌单（伤感、古风）
  final AlgerApiService _algerApi = AlgerApiService();
  AlgerPlaylist? _classicSad;
  AlgerPlaylist? _classicAncient;
  bool _isLoadingClassic = true;

  // 推荐歌单：默认拉取 5 个
  List<AlgerPlaylist> _recommendedPlaylists = [];
  bool _isLoadingRecommendedPlaylists = true;

  // 推荐艺人：只获取 6 名
  List<AlgerArtist> _recommendedArtists = [];
  bool _isLoadingArtists = true;


  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 4, vsync: this);
    _startBannerTimer();
    _loadHotSongs();
    _loadNewSongs();
    _loadFavorites();
    _loadCustomPlaylist();
    _loadPlaylists();
    _loadHistory();
    _checkVersionOnStartup();
    _loadClassicPlaylists();
    _loadRecommendedPlaylists();
    _loadRecommendedArtists();

    // 监听收藏状态变化
    FavoritesService.addListener(_onFavoritesChanged);
    // 监听自定义歌单变化
    CustomPlaylistService.addListener(_onCustomPlaylistChanged);
    // 监听多歌单变更，实时刷新
    PlaylistManagementService.addListener(_onPlaylistsChanged);
    
    // 监听历史记录变化
    HistoryService.addListener(_onHistoryChanged);
  }

  Future<void> _loadRecommendedArtists() async {
    setState(() => _isLoadingArtists = true);
    try {
      final list = await _algerApi.fetchTopArtists(limit: 6, offset: 0);
      if (mounted) {
        setState(() {
          _recommendedArtists = list.take(6).toList();
        });
      }
    } catch (e) {
      debugPrint('加载推荐艺人失败: $e');
    } finally {
      if (mounted) setState(() => _isLoadingArtists = false);
    }
  }

  Future<void> _loadRecommendedPlaylists() async {
    setState(() => _isLoadingRecommendedPlaylists = true);
    try {
      final list = await _algerApi.fetchTopPlaylists(cat: '全部', limit: 5, offset: 0);
      setState(() {
        _recommendedPlaylists = list.take(5).toList();
      });
    } catch (e) {
      debugPrint('加载推荐歌单失败: $e');
    } finally {
      if (mounted) setState(() => _isLoadingRecommendedPlaylists = false);
    }
  }

  Future<void> _loadClassicPlaylists() async {
    try {
      final sadList = await _algerApi.fetchTopPlaylists(cat: '伤感', limit: 1, offset: 0);
      final ancientList = await _algerApi.fetchTopPlaylists(cat: '古风', limit: 1, offset: 0);
      if (mounted) {
        setState(() {
          _classicSad = sadList.isNotEmpty ? sadList.first : null;
          _classicAncient = ancientList.isNotEmpty ? ancientList.first : null;
          _isLoadingClassic = false;
        });
      }
    } catch (e) {
      if (mounted) {
        setState(() {
          _isLoadingClassic = false;
        });
      }
    }
  }

  @override
  void dispose() {
    _bannerTimer?.cancel();
    _bannerController.dispose();
    _tabController.dispose();
    FavoritesService.removeListener(_onFavoritesChanged);
    HistoryService.removeListener(_onHistoryChanged);
    CustomPlaylistService.removeListener(_onCustomPlaylistChanged);
    PlaylistManagementService.removeListener(_onPlaylistsChanged);
    super.dispose();
  }

  void _startBannerTimer() {
    _bannerTimer = Timer.periodic(const Duration(seconds: 3), (timer) {
      if (_bannerController.hasClients) {
        final nextIndex = (_currentBannerIndex + 1) % _bannerItems.length;
        _bannerController.animateToPage(
          nextIndex,
          duration: const Duration(milliseconds: 300),
          curve: Curves.easeInOut,
        );
      }
    });
  }

  Future<void> _checkVersionOnStartup() async {
    await CommonUtils.checkAndPromptUpdate(context, manual: false);
  }

  Future<void> _loadHotSongs() async {
    try {
      final apiService = MusicApiService();
      final results = await apiService.getMituMusic(
        type: 'hot', // 使用知名歌手名获取热门歌曲
        count: 5,
      );
      // 预先获取每首歌的专辑图片URL，便于列表中直接显示
      final enriched = await Future.wait(results.take(10).map((song) async {
        final url = await apiService.getAlbumPicture(
          picId: song.picId,
          source: MusicSource.fromString(song.source),
          size: 300,
        );
        return song.copyWith(albumImageUrl: url);
      }));
      if (mounted) {
        setState(() {
          _hotSongs = enriched.toList(); // 显示前15首并包含专辑图
          _isLoadingHotSongs = false;
        });
      }
    } catch (e) {
      if (mounted) {
        setState(() {
          _isLoadingHotSongs = false;
        });
      }
    }
  }

  Future<void> _loadNewSongs() async {
    try {
      final apiService = MusicApiService();
      final results = await apiService.getMituMusic(
        type: 'new', // 使用知名歌手名获取热门歌曲
        count: 5
      );
      // 预先获取每首歌的专辑图片URL，便于列表中直接显示
      final enriched = await Future.wait(results.take(10).map((song) async {
        final url = await apiService.getAlbumPicture(
          picId: song.picId,
          source: MusicSource.fromString(song.source),
          size: 300,
        );
        return song.copyWith(albumImageUrl: url);
      }));
      if (mounted) {
        setState(() {
          _newSongs = enriched.toList(); // 显示前15首新歌并包含专辑图
          _isLoadingNewSongs = false;
        });
      }
    } catch (e) {
      if (mounted) {
        setState(() {
          _isLoadingNewSongs = false;
        });
      }
    }
  }

  Future<void> _loadFavorites() async {
    try {
      final favorites = await FavoritesService.getFavorites();
      if (mounted) {
        setState(() {
          _favoriteSongs = favorites; // 显示所有收藏歌曲
          _isLoadingFavorites = false;
        });
      }
    } catch (e) {
      if (mounted) {
        setState(() {
          _isLoadingFavorites = false;
        });
      }
    }
  }

  Future<void> _loadCustomPlaylist() async {
    try {
      final playlist = await CustomPlaylistService.getPlaylist();
      if (mounted) {
        setState(() {
          _customPlaylistSongs = playlist;
          _isLoadingCustomPlaylist = false;
        });
      }
    } catch (e) {
      if (mounted) {
        setState(() {
          _isLoadingCustomPlaylist = false;
        });
      }
    }
  }

  Future<void> _loadHistory() async {
    try {
      final history = await HistoryService.getHistory();
      if (mounted) {
        setState(() {
          _historySongs = history; // 显示所有历史歌曲
          _isLoadingHistory = false;
        });
      }
    } catch (e) {
      if (mounted) {
        setState(() {
          _isLoadingHistory = false;
        });
      }
    }
  }

  void _onFavoritesChanged() {
    // 当收藏状态改变时，重新加载收藏列表
    _loadFavorites();
  }

  void _onHistoryChanged() {
    // 当历史记录改变时，重新加载历史列表
    _loadHistory();
  }

  void _onCustomPlaylistChanged() {
    _loadCustomPlaylist();
  }

  void _onPlaylistsChanged() {
    _loadPlaylists();
  }

  Future<void> _loadPlaylists() async {
    try {
      final list = await PlaylistManagementService.getPlaylists();
      if (mounted) {
        setState(() {
          _playlists = list;
          _isLoadingPlaylists = false;
          // 初始化每个歌单的折叠状态（默认折叠）
          for (final p in list) {
            _playlistExpanded.putIfAbsent(p.id, () => false);
          }
        });
      }
    } catch (e) {
      if (mounted) {
        setState(() {
          _isLoadingPlaylists = false;
        });
      }
    }
  }

  Future<void> _createPlaylist() async {
    final controller = TextEditingController();
    final name = await showDialog<String>(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: const Text('新增歌单'),
          content: TextField(
            controller: controller,
            decoration: const InputDecoration(hintText: '请输入歌单名称'),
          ),
          actions: [
            TextButton(onPressed: () => Navigator.pop(context), child: const Text('取消')),
            TextButton(onPressed: () => Navigator.pop(context, controller.text.trim()), child: const Text('确定')),
          ],
        );
      },
    );
    if (name == null || name.isEmpty) return;
    await PlaylistManagementService.createPlaylist(name);
    await _loadPlaylists();
    if (mounted) {
      ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('已创建歌单 "$name"')));
    }
  }

  Future<void> _renamePlaylist(Playlist p) async {
    final controller = TextEditingController(text: p.name);
    final newName = await showDialog<String>(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: const Text('重命名歌单'),
          content: TextField(
            controller: controller,
            decoration: const InputDecoration(hintText: '请输入新的歌单名称'),
          ),
          actions: [
            TextButton(onPressed: () => Navigator.pop(context), child: const Text('取消')),
            TextButton(onPressed: () => Navigator.pop(context, controller.text.trim()), child: const Text('确定')),
          ],
        );
      },
    );
    if (newName == null || newName.isEmpty || newName == p.name) return;
    await PlaylistManagementService.renamePlaylist(p.id, newName);
    await _loadPlaylists();
    if (mounted) {
      ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('已重命名为 "$newName"')));
    }
  }

  Future<void> _deletePlaylist(Playlist p) async {
    final ok = await showDialog<bool>(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: const Text('删除歌单'),
          content: Text('确定要删除歌单 "${p.name}" 吗？此操作不可撤销。'),
          actions: [
            TextButton(onPressed: () => Navigator.pop(context, false), child: const Text('取消')),
            TextButton(onPressed: () => Navigator.pop(context, true), child: const Text('删除')),
          ],
        );
      },
    );
    if (ok != true) return;
    await PlaylistManagementService.deletePlaylist(p.id);
    _playlistExpanded.remove(p.id);
    await _loadPlaylists();
    if (mounted) {
      ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('已删除歌单 "${p.name}"')));
    }
  }

  void _showPlayerSheet() {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      // 默认桌面端会限制 BottomSheet 宽度，这里使用无限约束，
      // 让其根据父级（窗口）实时变化以达到自适应全屏。
      constraints: const BoxConstraints(
        maxWidth: double.infinity,
        maxHeight: double.infinity,
      ),
      useSafeArea: true,
      builder: (context) => const PlayerSheetWidget(),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        child: SafeArea(
          child: CustomScrollView(
            slivers: [
              SliverFillRemaining(
                child: _buildContent(),
              ),
            ],
          ),
        ),
      ),
      
      // 底部迷你播放器
      bottomNavigationBar: Consumer<MusicPlayerService>(
        builder: (context, playerService, child) {
          if (playerService.currentSong == null) {
            return const SizedBox.shrink();
          }         
          return MiniPlayerWidget(
            onTap: _showPlayerSheet,
          );
        },
      ),
    );
  }

  Widget _buildSearchBar() {
    return Padding(
      padding: const EdgeInsets.fromLTRB(16.0, 6.0, 16.0, 0.0),
      child: Container(
        height: 34,
        decoration: BoxDecoration(
          color: const Color.fromARGB(255, 211, 210, 210).withOpacity(0.2),
          borderRadius: BorderRadius.circular(18),
        ),
        child: Row(
          children: [
            // 搜索入口（保持原交互）
            Expanded(
              child: GestureDetector(
                onTap: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(builder: (context) => const SearchScreen()),
                  );
                },
                child: TextField(
                  readOnly: true,
                  style: const TextStyle(color: Colors.black87, fontSize: 14),
                  textAlignVertical: TextAlignVertical.center,
                  decoration: InputDecoration(
                    isDense: true,
                    hintText: '搜索歌曲、歌手',
                    hintStyle: TextStyle(color: Colors.black54, fontSize: 14),
                    prefixIcon: Icon(Icons.search, color: Colors.black45, size: 18),
                    border: InputBorder.none,
                    contentPadding: const EdgeInsets.symmetric(horizontal: 12),
                  ),
                  onTap: () {
                    Navigator.push(
                      context,
                      MaterialPageRoute(builder: (context) => const SearchScreen()),
                    );
                  },
                ),
              ),
            ),
            const SizedBox(width: 8),
            // 个人中心按钮
            IconButton(
              tooltip: '个人中心',
              icon: Icon(Icons.person, color: Colors.black.withOpacity(0.9), size: 20),
              onPressed: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(builder: (context) => const ProfilePage()),
                );
              },
            ),
          ],
        ),
      ),
    );
  }

//轮播图
  Widget _buildBannerCarousel() {
    return Column(
      children: [
        Container(
          height: 100,
          margin: const EdgeInsets.fromLTRB(16, 6, 16, 0),
          child: PageView.builder(
            controller: _bannerController,
            onPageChanged: (index) {
              setState(() {
                _currentBannerIndex = index;
              });
            },
            itemCount: _bannerItems.length,
            itemBuilder: (context, index) {
              final item = _bannerItems[index];
              return Container(
                margin: const EdgeInsets.symmetric(horizontal: 3),
                 child: ClipRRect(
                  borderRadius: BorderRadius.circular(16),
                child: Container(
                  decoration: BoxDecoration(
                    gradient: LinearGradient(
                      begin: Alignment.topLeft,
                      end: Alignment.bottomRight,
                      colors: [
                        item['color'],
                        item['color'].withOpacity(0.7),
                      ],
                    ),
                  ),
                  child: SvgPicture.asset(
                    item['image'],
                    fit: BoxFit.contain,
                    width: double.infinity,
                    height: double.infinity,
                    placeholderBuilder: (context) => Container(
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(16),
                          color: item['color'],
                        ),                   
                      child: const Center(
                        child: Icon(
                          Icons.music_note,
                          size: 50,
                          color: Colors.white70,
                        ),
                        ),
                      ),
                    ),
                  ),
                ),
              );
            },
          ),
        ),
        // 轮播图指示器
        Container(
          margin: const EdgeInsets.only(top: 8, bottom: 8),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: _bannerItems.asMap().entries.map((entry) {
              final index = entry.key;
              final isActive = index == _currentBannerIndex;
              return Container(
                width: isActive ? 20 : 6,
                height: 6,               
                margin: const EdgeInsets.symmetric(horizontal: 3),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(3),
                  color: isActive 
                    ? Colors.white 
                    : Colors.white.withOpacity(0.4),
                ),
              );
            }).toList(),
          ),
        ),
      ],
    );
  }

  Widget _buildNavigationTabs() {
    final tabs = ['推荐', '歌单', '排行榜', '艺人', 'MV', '我的收藏', '下载管理', '本地音乐', '最近播放'];
    return LayoutBuilder(
      builder: (context, constraints) {
        // 宽屏时隐藏顶部横向导航，改为左侧纵向导航
        final isWide = CommonUtils.isWideScreen(context);
        if (isWide) return const SizedBox.shrink();

        return Container(
          margin: const EdgeInsets.fromLTRB(16, 6, 16, 6),
          child: SingleChildScrollView(
            scrollDirection: Axis.horizontal,
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: tabs.asMap().entries.map((entry) {
              final index = entry.key;
              final title = entry.value;
              final isSelected = _selectedTabIndex == index;

              return GestureDetector(
                onTap: () {
                  setState(() {
                    _selectedTabIndex = index;
                  });
                },
                child: Container(
                  margin: const EdgeInsets.only(right: 8),
                  padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                  decoration: BoxDecoration(
                    color: isSelected ? Colors.black.withOpacity(0.2) : Colors.transparent,
                    borderRadius: BorderRadius.circular(16),
                  ),
                  child: Text(
                    title,
                    style: (isSelected
                            ? Theme.of(context).textTheme.labelLarge
                            : Theme.of(context).textTheme.labelMedium)
                        ?.copyWith(
                      color: isSelected ? Colors.black : Colors.black.withOpacity(0.7),
                    ),
                  ),
                ),
              );
              }).toList(),
            ),
          ),
        );
      },
    );
  }

  Widget _buildContent() {
    return LayoutBuilder(
      builder: (context, constraints) {
        final isWide = CommonUtils.isWideScreen(context);
        if (!isWide) {
          // 窄屏：维持现有白色内容容器 + 顶部横向导航
          return Container(
            decoration: const BoxDecoration(
              color: Colors.white,
            ),
            child: SingleChildScrollView(
              child: Column(
                children: [
                  _buildSearchBar(), // 顶部搜索栏
                  const SizedBox(width: 5),
                  _buildNavigationTabs(), // 顶部横向导航
                  const SizedBox(width: 5),
                  _buildTabContent(), // 内容区域
                ],
              ),
            ),
          );
        }

        // 宽屏：左侧纵向导航 + 右侧内容
        return Container(
          decoration: const BoxDecoration(
            color: Colors.white,
          ),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 左侧导航
              Container(
                width: 160,
                padding: const EdgeInsets.fromLTRB(12, 12, 12, 12),
                // 菜单
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Image.asset(
                      'assets/images/tray_icon.png',
                      width: 60,
                      height: 60,
                    ),
                    // 菜单
                    _buildSideNavigation(),
                  ],
                ),
                decoration: BoxDecoration(
                  border: Border(
                    right: BorderSide(
                      color: const Color.fromARGB(255, 61, 57, 57).withOpacity(0.2),
                      width: 1,
                    ),
                  ),
                ),
              ),
              // 右侧内容
              Expanded(
                child: SingleChildScrollView(
                  child: _buildTabContent(),
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  Widget _buildSideNavigation() {
    final tabs = ['推荐', '歌单', '排行榜', '艺人', 'MV', '我的收藏', '下载管理', '本地音乐', '最近播放'];
    return Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: tabs.asMap().entries.map((entry) {
        final index = entry.key;
        final title = entry.value;
        final isSelected = _selectedTabIndex == index;
        return GestureDetector(
          onTap: () {
            setState(() {
              _selectedTabIndex = index;
            });
          },
          child: Container(
            margin: const EdgeInsets.symmetric(vertical: 4),
            padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
            decoration: BoxDecoration(
              color: isSelected ? Colors.blue.withOpacity(0.08) : Colors.transparent,
              borderRadius: BorderRadius.circular(10),
            ),
            child: Row(
              children: [
                Container(
                  width: 4,
                  height: 2,
                  decoration: BoxDecoration(
                    color: isSelected ? Colors.blueAccent : Colors.grey[400],
                    shape: BoxShape.circle,
                  ),
                ),
                const SizedBox(width: 2),
                Text(
                  title,
                  style: (isSelected
                          ? Theme.of(context).textTheme.labelLarge
                          : Theme.of(context).textTheme.labelMedium)
                      ?.copyWith(
                    color: isSelected ? Colors.blue[800] : Colors.black87,
                    fontSize: 13,
                  ),
                ),
              ],
            ),
          ),
        );
      }).toList(),
    );
  }

  // final tabs = ['推荐', '歌单', '排行榜', '艺人', 'MV', '我的收藏', '下载管理', '本地音乐', '最近播放'];
  Widget _buildTabContent() {
    switch (_selectedTabIndex) {
      case 0: // 推荐
        return _buildRecommendContent();
      case 1: // 歌单
        return _buildPlaylistContent();
      case 2: // 排行榜
        return _buildRankingContent();
      case 3: // 艺人
        return _buildArtistContent();
      case 4: // MV
        return _buildMvContent();
      case 5: // 我的收藏
        return _buildFavoritesContent();
      case 6: // 下载管理
        return _buildDownloadContent();
      case 7: // 本地音乐
        return _buildLocalMusicContent();
      case 8: // 最近播放
        return _buildHistoryContent();
      default:
        return _buildRecommendContent();
    }
  }

  Widget _buildRecommendContent() {
    return LayoutBuilder(
      builder: (context, constraints) {
        final isWideScreen = CommonUtils.isWideScreen(context);
        if (isWideScreen) {
          // 宽屏：右侧内容区顶部展示轮播图，左侧为菜单（由父布局控制）
          return Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              _buildSearchBar(), // 顶部搜索栏
              // const SizedBox(height: 5),
              // _buildBannerCarousel(),
              const SizedBox(height: 5),
              _buildArtistCards(),
              const SizedBox(height: 5),
              _buildRecommendedPlaylist(),
              const SizedBox(height: 5),
              Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Expanded(
                    flex: 1,
                    child: _buildHotSongsList(),
                  ),
                  const SizedBox(width: 16),
                  Expanded(
                    flex: 1,
                    child: _buildNewSongsList(),
                  ),
                ],
              ),
              const SizedBox(height: 5),
              _buildPersonalizedCards(),
              const SizedBox(height: 5),
              _buildClassic(),
            ],
          );
        } else {
          // 窄屏：内容区顶部展示轮播图
          return Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // const SizedBox(height: 5),
              // _buildBannerCarousel(),
              const SizedBox(height: 5),
              _buildArtistCards(),
              const SizedBox(height: 5),
              _buildRecommendedPlaylist(),
              const SizedBox(height: 5),
              _buildHotSongsList(),
              const SizedBox(height: 5),
              _buildNewSongsList(),
              const SizedBox(height: 5),
              _buildPersonalizedCards(),
              const SizedBox(height: 5),
              _buildClassic(),
            ],
          );
        }
      },
    );
  }


  Widget _buildPlaylistContent() {
    return const AlgerPlaylistScreen();
  }

  Widget _buildArtistContent() {
    return const  AlgerArtistsScreen();
  }

  Widget _buildDownloadContent() {
    return const Center(
      child: Text('下载管理'),
    );
  }

  Widget _buildMvContent() {
    return const AlgerMvListScreen();
  }

  Widget _buildLocalMusicContent() {
    return const Center(
      child: Text('本地音乐'),
    );
  }

  Widget _buildRecommendCategories() {
    final items = ['歌手', '排行榜', '歌单分类', '听书', '音乐现场', '会员专区'];
    return Container(
      margin: const EdgeInsets.fromLTRB(16, 8, 16, 0),
      child: SingleChildScrollView(
        scrollDirection: Axis.horizontal,
        child: Row(
          children: items.map((e) {
            return Padding(
              padding: const EdgeInsets.only(right: 8),
              child: GestureDetector(
                onTap: () {},
                child: Container(
                  padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(18),
                    border: Border.all(color: Colors.grey[300]!),
                  ),
                  child: Text(
                    e,
                    style: TextStyle(fontSize: 12, color: Colors.grey[800]),
                  ),
                ),
              ),
            );
          }).toList(),
        ),
      ),
    );
  }

  // 推荐歌单
  Widget _buildRecommendedPlaylist() {
    return Container(
      margin: const EdgeInsets.fromLTRB(16, 5, 16, 10),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              const Text(
                '推荐歌单',
                style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
              ),
              const Spacer(),
              TextButton.icon(
                onPressed: () {
                  setState(() {
                    _selectedTabIndex = 1; // 切换到“歌单”页
                  });
                },
                label: const Text('查看更多'),
                style: TextButton.styleFrom(
                  padding: const EdgeInsets.symmetric(horizontal: 8),
                  minimumSize: const Size(0, 0),
                ),
              ),
            ],
          ),
          const SizedBox(height: 8),
          if (_isLoadingRecommendedPlaylists)
            const Center(child: Padding(padding: EdgeInsets.all(16), child: CircularProgressIndicator()))
          else if (_recommendedPlaylists.isEmpty)
            Container(
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(12),
                border: Border.all(color: Colors.black12),
              ),
              child: const Text('暂无推荐歌单', style: TextStyle(color: Colors.grey)),
            )
          else
            SizedBox(
              height: 140,
              child: ListView.separated(
                scrollDirection: Axis.horizontal,
                itemCount: _recommendedPlaylists.length,
                separatorBuilder: (_, __) => const SizedBox(width: 12),
                padding: const EdgeInsets.symmetric(horizontal: 4),
                itemBuilder: (context, index) {
                  final p = _recommendedPlaylists[index];
                  return _buildRecommendedPlaylistCard(p);
                },
              ),
            ),
        ],
      ),
    );
  }

  Widget _buildRecommendedPlaylistCard(AlgerPlaylist p) {
    return InkWell(
      onTap: () {
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (_) => AlgerPlaylistDetailScreen(
              playlistId: p.id,
              playlistName: p.name,
              coverImgUrl: p.coverImgUrl,
            ),
          ),
        );
      },
      child: Container(
        width: 140,
        height: 100,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(12),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.06),
              blurRadius: 8,
              offset: const Offset(0, 4),
            ),
          ],
        ),
        child: ClipRRect(
          borderRadius: BorderRadius.circular(12),
          child: Stack(
            children: [
              Positioned.fill(
                child: Image.network(
                  p.coverImgUrl,
                  fit: BoxFit.cover,
                  filterQuality: FilterQuality.medium,
                ),
              ),
              Positioned(
                left: 0,
                right: 0,
                bottom: 0,
                child: Container(
                  padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 8),
                  decoration: BoxDecoration(
                    gradient: LinearGradient(
                      begin: Alignment.bottomCenter,
                      end: Alignment.topCenter,
                      colors: [
                        Colors.black.withOpacity(0.5),
                        Colors.black.withOpacity(0.0),
                      ],
                    ),
                  ),
                  child: Text(
                    p.name,
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: const TextStyle(color: Colors.white, fontSize: 13, fontWeight: FontWeight.w600),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  // 经典
  Widget _buildClassic(){
    final playlists = [
      if (_classicSad != null) _classicSad!,
      if (_classicAncient != null) _classicAncient!,
    ];

    return Container(
      margin: const EdgeInsets.fromLTRB(16, 8, 16, 0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            '经典 | 华语音乐的黄金年代',
            style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
          ),
          const SizedBox(height: 8),
          if (_isLoadingClassic)
            const Center(child: Padding(padding: EdgeInsets.all(16), child: CircularProgressIndicator()))
          else if (playlists.isEmpty)
            Container(
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(12),
                border: Border.all(color: Colors.black12),
              ),
              child: const Text('暂无经典歌单', style: TextStyle(color: Colors.grey)),
            )
          else
            Container(
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(12),
                border: Border.all(color: Colors.black12),
                boxShadow: [
                  BoxShadow(color: Colors.black.withOpacity(0.03), blurRadius: 6, offset: const Offset(0, 2)),
                ],
              ),
              child: ListView.separated(
                shrinkWrap: true,
                physics: const NeverScrollableScrollPhysics(),
                itemCount: playlists.length,
                separatorBuilder: (_, __) => const Divider(height: 1, thickness: 0.5, color: Colors.black12),
                itemBuilder: (context, index) => _buildClassicItem(playlists[index]),
              ),
            ),
        ],
      ),
    );
  }

  Widget _buildClassicItem(AlgerPlaylist playlist) {
    return InkWell(
      onTap: () async {
        final tracks = await _algerApi.fetchPlaylistTracks(playlist.id);
        final player = Provider.of<MusicPlayerService>(context, listen: false);
        if (tracks.isNotEmpty) {
          await player.setPlaylist(tracks, startIndex: 0);
        } else {
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(content: Text('该歌单暂无可播放歌曲')),
          );
        }
      },
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 14),
        child: Row(
          children: [
            ClipRRect(
              borderRadius: BorderRadius.circular(10),
              child: SizedBox(
                width: 72,
                height: 72,
                child: Image.network(
                  playlist.coverImgUrl,
                  fit: BoxFit.cover,
                  errorBuilder: (context, error, stack) => Container(
                    color: Colors.grey[200],
                    child: const Icon(Icons.music_note, color: Colors.grey),
                  ),
                ),
              ),
            ),
            const SizedBox(width: 14),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    playlist.name,
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: const TextStyle(fontSize: 15, fontWeight: FontWeight.w600, color: Colors.black87),
                  ),
                  const SizedBox(height: 8),
                  Row(
                    children: [
                      Icon(Icons.play_arrow, size: 16, color: Colors.redAccent.shade200),
                      const SizedBox(width: 4),
                      Text(
                        _formatPlayCount(playlist.playCount),
                        style: TextStyle(fontSize: 12, color: Colors.grey[600]),
                      ),
                    ],
                  ),
                ],
              ),
            ),
            const SizedBox(width: 8),
            Icon(Icons.play_circle_outline, color: Colors.grey[700], size: 24),
          ],
        ),
      ),
    );
  }

  String _formatPlayCount(int count) {
    if (count >= 100000000) {
      return '${(count / 100000000).toStringAsFixed(1)}亿';
    } else if (count >= 10000) {
      return '${(count / 10000).toStringAsFixed(1)}万';
    }
    return count.toString();
  }

  // 推荐艺人（仅取 6 名），窄屏单行横向滚动
  Widget _buildArtistCards() {
    final spacing = 24.0;
    final avatarSize = CommonUtils.isWideScreen(context) ? 90.0 : 72.0;
    Widget buildItem(AlgerArtist a) {
      return GestureDetector(
        onTap: () {
          Navigator.push(
            context,
            MaterialPageRoute(
              builder: (_) => AlgerArtistDetailScreen(
                artistId: a.id,
                artistName: a.name,
                picUrl: a.picUrl,
              ),
            ),
          );
        },
        child: SizedBox(
          width: avatarSize + 20,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              ClipOval(
                child: SizedBox(
                  width: avatarSize,
                  height: avatarSize,
                  child: CachedNetworkImage(
                    imageUrl: a.picUrl,
                    fit: BoxFit.cover,
                    memCacheWidth: 200,
                    memCacheHeight: 200,
                    maxWidthDiskCache: 200,
                    maxHeightDiskCache: 200,
                    placeholder: (context, url) => Container(color: Colors.grey[200]),
                    errorWidget: (context, url, error) => Container(color: Colors.grey[300], child: const Icon(Icons.person, size: 32)),
                  ),
                ),
              ),
              const SizedBox(height: 8),
              Text(
                a.name,
                style: const TextStyle(fontSize: 13, color: Colors.black87),
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                textAlign: TextAlign.center,
              ),
            ],
          ),
        ),
      );
    }

    return Container(
      margin: const EdgeInsets.fromLTRB(16, 8, 16, 0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // const Text(
          //   '推荐艺人',
          //   style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
          // ),
          // const SizedBox(height: 12),
          if (_isLoadingArtists)
            SizedBox(
              height: avatarSize + 36,
              child: ListView.separated(
                scrollDirection: Axis.horizontal,
                itemCount: 6,
                separatorBuilder: (_, __) => SizedBox(width: spacing),
                itemBuilder: (_, __) => Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    ClipOval(
                      child: Container(
                        width: avatarSize,
                        height: avatarSize,
                        color: Colors.grey[200],
                      ),
                    ),
                    const SizedBox(height: 8),
                    Container(width: avatarSize, height: 12, color: Colors.grey[200]),
                  ],
                ),
              ),
            )
          else if (_recommendedArtists.isEmpty)
            const Text('暂无推荐艺人', style: TextStyle(color: Colors.grey))
          else
            // 始终单行展示；不足宽度时可横向滑动
            SizedBox(
              height: avatarSize + 36,
              child: ListView.separated(
                scrollDirection: Axis.horizontal,
                itemCount: _recommendedArtists.length,
                separatorBuilder: (_, __) => SizedBox(width: spacing),
                itemBuilder: (_, i) => buildItem(_recommendedArtists[i]),
              ),
            ),
        ],
      ),
    );
  }

  //个性推荐
  Widget _buildPersonalizedCards() {
    final isWide = CommonUtils.isWideScreen(context);
    final spacing = 12.0;
    final baseTileWidth = 180.0;
    final baseTileHeight = 120.0;
    final tiles = [
      {
        'title': '大家都在听',
        'color':  const Color.fromARGB(255, 197, 189, 81),
        'icon': Icons.groups,
        'keyword': '大家都在听'
      },
      {
        'title': '怀旧90后',
        'color': const Color.fromARGB(255, 115, 197, 186),
        'icon': Icons.history,
        'keyword': '90后'
      },
      {
        'title': '车载音乐',
        'color': const Color.fromARGB(255, 10, 32, 107),
        'icon': Icons.directions_car,
        'keyword': '车载'
      },
    ];

    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            '个性推荐',
            style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: Colors.black87),
          ),
          const SizedBox(height: 12),
          LayoutBuilder(
            builder: (context, constraints) {
              // 当屏幕较窄时，使用横向滚动的单行列表，避免自动换到第二行
              final singleRowNeededWidth = baseTileWidth * tiles.length + spacing * (tiles.length - 1);
              final isNarrow = constraints.maxWidth < singleRowNeededWidth;
              final tileWidth = baseTileWidth;
              final tileHeight = baseTileHeight;

              Widget tile(Widget child) => SizedBox(width: tileWidth, height: tileHeight, child: child);

              if (isNarrow) {
                return SizedBox(
                  height: tileHeight,
                  child: ListView.separated(
                    scrollDirection: Axis.horizontal,
                    padding: EdgeInsets.zero,
                    itemCount: tiles.length,
                    separatorBuilder: (_, __) => SizedBox(width: spacing),
                    itemBuilder: (_, i) {
                      final t = tiles[i];
                      return tile(
                        RankingImageGenerator.buildRankingCardWithImage(
                          title: t['title'] as String,
                          backgroundColor: t['color'] as Color,
                          icon: t['icon'] as IconData,
                          onTap: () => _navigateToRankingScreen(t['keyword'] as String, t['title'] as String),
                        ),
                      );
                    },
                  ),
                );
              }

              // 宽屏保持单行居中展示
              return Center(
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    for (int i = 0; i < tiles.length; i++) ...[
                      if (i != 0) SizedBox(width: spacing),
                      tile(
                        RankingImageGenerator.buildRankingCardWithImage(
                          title: tiles[i]['title'] as String,
                          backgroundColor: tiles[i]['color'] as Color,
                          icon: tiles[i]['icon'] as IconData,
                          onTap: () => _navigateToRankingScreen(tiles[i]['keyword'] as String, tiles[i]['title'] as String),
                        ),
                      ),
                    ]
                  ],
                ),
              );
            },
          ),
        ],
      ),
    );
  }

  void _navigateToCategory(String keyword, String title) {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => SearchScreen(initialKeyword: keyword),
      ),
    );
  }

  Widget _buildHotSongsList() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const SizedBox(height: 20),
        Padding(
          padding: const EdgeInsets.symmetric(horizontal: 16),
          child: Row(
            children: [
              const Text(
                '热门',
                style: TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                  color: Colors.black87,
                ),
              ),
            ],
          ),
        ),
        const SizedBox(height: 16),
        if (_isLoadingHotSongs)
          const Center(
            child: Padding(
              padding: EdgeInsets.all(20),
              child: CircularProgressIndicator(),
            ),
          )
        else if (_hotSongs.isEmpty)
          const Center(
            child: Padding(
              padding: EdgeInsets.all(20),
              child: Text(
                '暂无热门歌曲',
                style: TextStyle(
                  color: Colors.grey,
                  fontSize: 14,
                ),
              ),
            ),
          )
        else if (_isHotSongsExpanded)
          Container(
            margin: const EdgeInsets.symmetric(horizontal: 16),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(12),
              border: Border.all(color: Colors.black12),
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withOpacity(0.03),
                  blurRadius: 6,
                  offset: const Offset(0, 2),
                ),
              ],
            ),
            child: ListView.separated(
              shrinkWrap: true,
              physics: const NeverScrollableScrollPhysics(),
              itemCount: (_hotSongs.length),
              separatorBuilder: (_, __) => const Divider(height: 1, thickness: 0.5, color: Colors.black12),
              itemBuilder: (context, index) {
                final song = _hotSongs[index];
                return _buildHotSongItem(song, index + 1);
              },
            ),
          ),
      ],
    );
  }

  Widget _buildNewSongsList() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const SizedBox(height: 20),
        Padding(
          padding: const EdgeInsets.symmetric(horizontal: 16),
          child: Row(
            children: [
              const Text(
                '最新',
                style: TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                  color: Colors.black87,
                ),
              ),
            ],
          ),
        ),
        const SizedBox(height: 16),
        if (_isLoadingNewSongs)
          const Center(
            child: Padding(
              padding: EdgeInsets.all(20),
              child: CircularProgressIndicator(),
            ),
          )
        else if (_newSongs.isEmpty)
          const Center(
            child: Padding(
              padding: EdgeInsets.all(20),
              child: Text(
                '暂无新歌',
                style: TextStyle(
                  color: Colors.grey,
                  fontSize: 14,
                ),
              ),
            ),
          )
        else if (_isNewSongsExpanded)
          Container(
            margin: const EdgeInsets.symmetric(horizontal: 16),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(12),
              border: Border.all(color: Colors.black12),
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withOpacity(0.03),
                  blurRadius: 6,
                  offset: const Offset(0, 2),
                ),
              ],
            ),
            child: ListView.separated(
              shrinkWrap: true,
              physics: const NeverScrollableScrollPhysics(),
              itemCount: (_newSongs.length),
              separatorBuilder: (_, __) => const Divider(height: 1, thickness: 0.5, color: Colors.black12),
              itemBuilder: (context, index) {
                final song = _newSongs[index];
                return _buildNewSongItem(song, index + 1);
              },
            ),
          ),
      ],
    );
  }

  Widget _buildRankingContent() {
    return const AlgerToplistScreen();
  }

  void _navigateToRankingScreen(String type, String title) {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => RankingScreen(
          rankingType: type,
          title: title,
        ),
      ),
    );
  }

  Widget _buildFavoritesContent() {
    return SingleChildScrollView(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const SizedBox(height: 20),
          // 我喜欢分区
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 16),
            child: Row(
              children: [
                GestureDetector(
                  onTap: () => setState(() => _isFavoritesExpanded = !_isFavoritesExpanded),
                  child: Row(
                    children: [
                      Icon(Icons.favorite, size: 18, color: Colors.redAccent.shade200),
                      const SizedBox(width: 4),
                      const Text(
                        '我喜欢',
                        style: TextStyle(
                          fontSize: 18,
                          fontWeight: FontWeight.bold,
                          color: Colors.black87,
                        ),
                      ),
                    ],
                  ),
                ),
                const Spacer(),
                Text(
                  '${_favoriteSongs.length}首',
                  style: TextStyle(
                    fontSize: 14,
                    color: Colors.grey[600],
                  ),
                ),
                const SizedBox(width: 8),
                _buildActionChip(label: '导出', icon: Icons.download, onTap: _exportFavorites),
                const SizedBox(width: 8),
                _buildActionChip(label: '导入', icon: Icons.upload, onTap: _importFavorites),
              ],
            ),
          ),
          const SizedBox(height: 16),
          if (_isLoadingFavorites)
            const Padding(
              padding: EdgeInsets.all(20),
              child: Center(child: CircularProgressIndicator()),
            )
          else if (!_isFavoritesExpanded)
            const SizedBox.shrink()
          else if (_favoriteSongs.isEmpty)
            Padding(
              padding: const EdgeInsets.all(20),
              child: Center(
                child: Text(
                  '还没有收藏的歌曲',
                  style: TextStyle(
                    fontSize: 14,
                    color: Colors.grey[600],
                  ),
                ),
              ),
            )
          else
            ListView.builder(
              padding: const EdgeInsets.symmetric(horizontal: 16),
              shrinkWrap: true,
              physics: const NeverScrollableScrollPhysics(),
              itemCount: _favoriteSongs.length,
              itemBuilder: (context, index) {
                final song = _favoriteSongs[index];
                return _buildFavoriteItem(song, index + 1);
              },
            ),

          const SizedBox(height: 24),

          // 自定义歌单分区
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 16),
            child: Row(
              children: [
                GestureDetector(
                  onTap: () => setState(() => _isCustomPlaylistsExpanded = !_isCustomPlaylistsExpanded),
                  child: Row(
                    children: const [
                      Icon(Icons.queue_music, size: 18, color: Colors.black54),
                      SizedBox(width: 4),
                      Text(
                        '自定义歌单',
                        style: TextStyle(
                          fontSize: 18,
                          fontWeight: FontWeight.bold,
                          color: Colors.black87,
                        ),
                      ),
                    ],
                  ),
                ),
                const Spacer(),
                Text(
                  '${_playlists.length}个',
                  style: TextStyle(
                    fontSize: 14,
                    color: Colors.grey[600],
                  ),
                ),
                const SizedBox(width: 8),
                _buildActionChip(label: '新增', icon: Icons.add, onTap: _createPlaylist),
              ],
            ),
          ),
          const SizedBox(height: 16),
          if (_isLoadingPlaylists)
            const Padding(
              padding: EdgeInsets.all(20),
              child: Center(child: CircularProgressIndicator()),
            )
          else if (!_isCustomPlaylistsExpanded)
            const SizedBox.shrink()
          else if (_playlists.isEmpty)
            Padding(
              padding: const EdgeInsets.all(20),
              child: Center(
                child: Text(
                  '还没有创建自定义歌单',
                  style: TextStyle(
                    fontSize: 14,
                    color: Colors.grey[600],
                  ),
                ),
              ),
            )
          else
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 16),
              child: Column(
                children: _playlists.map((p) {
                  final expanded = _playlistExpanded[p.id] ?? false;
                  return Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Container(
                        margin: const EdgeInsets.only(bottom: 8),
                        padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                        decoration: BoxDecoration(
                          color: Colors.grey[100],
                          borderRadius: BorderRadius.circular(8),
                        ),
                        child: Row(
                          children: [
                            GestureDetector(
                              onTap: () => setState(() => _playlistExpanded[p.id] = !expanded),
                              child: Icon(
                                expanded ? Icons.expand_more : Icons.chevron_right,
                                size: 20,
                                color: Colors.black54,
                              ),
                            ),
                            const SizedBox(width: 5),
                            Expanded(
                              child: GestureDetector(
                                onTap: () => setState(() => _playlistExpanded[p.id] = !expanded),
                                child: Tooltip(
                                  message: p.name,
                                  waitDuration: const Duration(milliseconds: 300),
                                  child: Text(
                                    p.name,
                                    style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w600),
                                    maxLines: 1,
                                    overflow: TextOverflow.ellipsis,
                                    softWrap: false,
                                  ),
                                ),
                              ),
                            ),
                            Text(
                              '${p.songs.length}首',
                              style: TextStyle(fontSize: 12, color: Colors.grey[600]),
                            ),
                            const SizedBox(width: 5),
                            IconButton(
                              icon: const Icon(Icons.download, size: 18),
                              tooltip: '导出歌单',
                              onPressed: () => _exportPlaylist(p),
                            ),
                            IconButton(
                              icon: const Icon(Icons.upload, size: 18),
                              tooltip: '导入歌单',
                              onPressed: () => _importPlaylist(p),
                            ),
                            IconButton(
                              icon: const Icon(Icons.edit, size: 18),
                              tooltip: '重命名',
                              onPressed: () => _renamePlaylist(p),
                            ),
                            IconButton(
                              icon: Icon(Icons.delete_outline, size: 18, color: Colors.red[400]),
                              tooltip: '删除',
                              onPressed: () => _deletePlaylist(p),
                            ),
                          ],
                        ),
                      ),
                      if (expanded)
                        ListView.builder(
                          padding: const EdgeInsets.only(left: 0, right: 0, bottom: 8),
                          shrinkWrap: true,
                          physics: const NeverScrollableScrollPhysics(),
                          itemCount: p.songs.length,
                          itemBuilder: (context, index) {
                            final song = p.songs[index];
                            return _buildPlaylistSongItem(song, index + 1, p.songs, p.id);
                          },
                        ),
                    ],
                  );
                }).toList(),
              ),
            ),
          const SizedBox(height: 12),
        ],
      ),
    );
  }

  Widget _buildActionChip({required String label, required IconData icon, required VoidCallback onTap}) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
        decoration: BoxDecoration(
          color: Colors.blue.withOpacity(0.08),
          borderRadius: BorderRadius.circular(12),
          border: Border.all(color: Colors.blue.withOpacity(0.3)),
        ),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            Icon(icon, size: 16, color: Colors.blue[600]),
            const SizedBox(width: 4),
            Text(
              label,
              style: TextStyle(
                fontSize: 12,
                color: Colors.blue[600],
                fontWeight: FontWeight.w500,
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildPlaylistSongItem(Song song, int index, List<Song> list, String playlistId) {
    return GestureDetector(
      onTap: () async {
        final playerService = Provider.of<MusicPlayerService>(context, listen: false);
        await playerService.setPlaylist(list, startIndex: index - 1);
      },
      child: Container(
        margin: const EdgeInsets.only(bottom: 8),
        padding: const EdgeInsets.all(12),
        decoration: BoxDecoration(
          color: Colors.grey[50],
          borderRadius: BorderRadius.circular(8),
        ),
        child: Row(
          children: [
            Container(
              width: 24,
              height: 24,
              decoration: BoxDecoration(
                color: Colors.grey[300],
                borderRadius: BorderRadius.circular(4),
              ),
              child: Center(
                child: Text(
                  '$index',
                  style: const TextStyle(
                    fontSize: 12,
                    fontWeight: FontWeight.bold,
                    color: Colors.black54,
                  ),
                ),
              ),
            ),
            const SizedBox(width: 12),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    song.name,
                    style: const TextStyle(
                      fontSize: 14,
                      fontWeight: FontWeight.w500,
                      color: Colors.black87,
                    ),
                  ),
                  const SizedBox(height: 2),
                  Text(
                    song.artistsString,
                    style: TextStyle(
                      fontSize: 12,
                      color: Colors.grey[600],
                    ),
                  ),
                ],
              ),
            ),
            IconButton(
              icon: Icon(Icons.delete_outline, size: 18, color: Colors.red[400]),
              tooltip: '移除',
              onPressed: () => _removeSongFromPlaylist(playlistId, song),
              padding: const EdgeInsets.all(4),
              constraints: const BoxConstraints(minWidth: 32, minHeight: 32),
            ),
            const SizedBox(width: 4),
            Icon(Icons.play_circle_outline, color: Colors.grey[600], size: 20),
          ],
        ),
      ),
    );
  }

  Future<void> _exportFavorites() async {
    try {
      if (Platform.isAndroid || Platform.isIOS) {
        final dir = await getTemporaryDirectory();
        final tempPath = '${dir.path}/favorites_export.json';
        final path = await FavoritesService.exportFavoritesToFile(tempPath);
        if (path == null) throw Exception('生成导出文件失败');
        await Share.shareXFiles([XFile(path!)], text: '分享“我喜欢”歌单文件');
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text('已导出并打开系统分享面板')),
          );
        }
      } else {
        const typeGroup = fs.XTypeGroup(label: 'JSON', extensions: ['json']);
        final location = await fs.getSaveLocation(
          acceptedTypeGroups: const [typeGroup],
          suggestedName: 'favorites_export.json',
        );
        if (location == null) return;
        final path = await FavoritesService.exportFavoritesToFile(location.path);
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text(path != null ? '已导出到: $path' : '导出失败')),
          );
        }
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('导出失败: $e')),
        );
      }
    }
  }

  Future<void> _importFavorites() async {
    try {
      const typeGroup = fs.XTypeGroup(label: 'JSON', extensions: ['json']);
      final file = await fs.openFile(acceptedTypeGroups: const [typeGroup]);
      if (file == null) return;
      final count = await FavoritesService.importFavoritesFromFile(file.path);
      await _loadFavorites();
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('已从 ${file.path} 导入 $count 首到“我喜欢”')),
        );
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('导入失败: $e')),
        );
      }
    }
  }

  Future<void> _exportCustomPlaylist() async {
    try {
      if (Platform.isAndroid || Platform.isIOS) {
        final dir = await getTemporaryDirectory();
        final tempPath = '${dir.path}/ly_music_custom_playlist.json';
        final path = await CustomPlaylistService.exportToFile(filePath: tempPath);
        if (path == null) throw Exception('生成导出文件失败');
        await Share.shareXFiles([XFile(path!)], text: '分享“自定义歌单”文件');
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text('已导出并打开系统分享面板')),
          );
        }
      } else {
        const typeGroup = fs.XTypeGroup(label: 'JSON', extensions: ['json']);
        final location = await fs.getSaveLocation(
          acceptedTypeGroups: const [typeGroup],
          suggestedName: 'ly_music_custom_playlist.json',
        );
        if (location == null) return;
        final path = await CustomPlaylistService.exportToFile(filePath: location.path);
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text(path != null ? '已导出到: $path' : '导出失败')),
          );
        }
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('导出失败: $e')),
        );
      }
    }
  }

  Future<void> _importCustomPlaylist() async {
    try {
      const typeGroup = fs.XTypeGroup(label: 'JSON', extensions: ['json']);
      final file = await fs.openFile(acceptedTypeGroups: const [typeGroup]);
      if (file == null) return;
      final count = await CustomPlaylistService.importFromFile(filePath: file.path);
      await _loadCustomPlaylist();
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('已从 ${file.path} 导入 $count 首到“自定义歌单”')),
        );
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('导入失败: $e')),
        );
      }
    }
  }

  Future<void> _exportPlaylist(Playlist p) async {
    try {
      if (Platform.isAndroid || Platform.isIOS) {
        final dir = await getTemporaryDirectory();
        final tempPath = '${dir.path}/${p.name}_export.json';
        final path = await PlaylistManagementService.exportPlaylistToFile(id: p.id, filePath: tempPath);
        await Share.shareXFiles([XFile(path)], text: '分享“${p.name}”歌单文件');
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('已导出并打开系统分享面板')));
        }
      } else {
        const typeGroup = fs.XTypeGroup(label: 'JSON', extensions: ['json']);
        final location = await fs.getSaveLocation(
          acceptedTypeGroups: const [typeGroup],
          suggestedName: '${p.name}_export.json',
        );
        if (location == null) return;
        final path = await PlaylistManagementService.exportPlaylistToFile(id: p.id, filePath: location.path);
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('已导出到: $path')));
        }
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('导出失败: $e')));
      }
    }
  }

  Future<void> _importPlaylist(Playlist p) async {
    try {
      const typeGroup = fs.XTypeGroup(label: 'JSON', extensions: ['json']);
      final file = await fs.openFile(acceptedTypeGroups: const [typeGroup]);
      if (file == null) return;
      final count = await PlaylistManagementService.importPlaylistFromFile(id: p.id, filePath: file.path);
      await _loadPlaylists();
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('已从 ${file.path} 导入 $count 首到 "${p.name}"')));
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('导入失败: $e')));
      }
    }
  }

  Future<void> _removeSongFromPlaylist(String playlistId, Song song) async {
    try {
      await PlaylistManagementService.removeSongFrom(playlistId, song);
      await _loadPlaylists();
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('已从歌单移除 "${song.name}"')));
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('移除失败: $e')));
      }
    }
  }

  void _openPlaylistManager() {
    // 已移除导航到管理页面，保留方法占位以避免潜在引用报错
  }

  Widget _buildHistoryContent() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const SizedBox(height: 20),
        Padding(
          padding: const EdgeInsets.symmetric(horizontal: 16),
          child: Row(
            children: [
              const Text(
                '播放历史',
                style: TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                  color: Colors.black87,
                ),
              ),
              const Spacer(),
              Text(
                '${_historySongs.length}首',
                style: TextStyle(
                  fontSize: 14,
                  color: Colors.grey[600],
                ),
              ),
              if (_historySongs.isNotEmpty) ...[
                const SizedBox(width: 8),
                GestureDetector(
                  onTap: _clearAllHistory,
                  child: Container(
                    padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                    decoration: BoxDecoration(
                      color: Colors.red.withOpacity(0.1),
                      borderRadius: BorderRadius.circular(12),
                      border: Border.all(color: Colors.red.withOpacity(0.3)),
                    ),
                    child: Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Icon(
                          Icons.clear_all,
                          size: 16,
                          color: Colors.red[600],
                        ),
                        const SizedBox(width: 4),
                        Text(
                          '一键清空',
                          style: TextStyle(
                            fontSize: 12,
                            color: Colors.red[600],
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ],
          ),
        ),
        const SizedBox(height: 16),
        if (_isLoadingHistory)
          const Padding(
            padding: EdgeInsets.all(20),
            child: Center(child: CircularProgressIndicator()),
          )
        else if (_historySongs.isEmpty)
          Padding(
            padding: const EdgeInsets.all(20),
            child: Center(
              child: Text(
                '还没有播放历史',
                style: TextStyle(
                  fontSize: 14,
                  color: Colors.grey[600],
                ),
              ),
            ),
          )
        else
          ListView.builder(
            padding: const EdgeInsets.symmetric(horizontal: 16),
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            itemCount: _historySongs.length,
            itemBuilder: (context, index) {
              final song = _historySongs[index];
              return _buildHistoryItemWithDelete(song);
            },
          ),
      ],
    );
  }

  Widget _buildHotSongItem(Song song, int index) {
    return InkWell(
      onTap: () async {
        final playerService = Provider.of<MusicPlayerService>(context, listen: false);
        await playerService.setPlaylist(_hotSongs, startIndex: index - 1);
      },
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
        child: Row(
        children: [
          Container(
            width: 24,
            height: 24,
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(6),
              border: Border.all(color: Colors.black12),
            ),
            child: Center(
              child: Text(
                '$index',
                style: const TextStyle(
                  fontSize: 12,
                  fontWeight: FontWeight.bold,
                  color: Colors.black54,
                ),
              ),
            ),
          ),
          const SizedBox(width: 12),
          // 专辑图显示在歌名前
          Container(
            width: 48,
            height: 48,
            decoration: BoxDecoration(
              color: Colors.grey[300],
              borderRadius: BorderRadius.circular(6),
            ),
            child: song.albumImageUrl != null && song.albumImageUrl!.isNotEmpty
                ? ClipRRect(
                    borderRadius: BorderRadius.circular(6),
                    child: Image.network(
                      song.albumImageUrl!,
                      fit: BoxFit.cover,
                      errorBuilder: (context, error, stackTrace) => const Icon(
                        Icons.music_note,
                        color: Colors.grey,
                        size: 20,
                      ),
                    ),
                  )
                : const Icon(
                    Icons.music_note,
                    color: Colors.grey,
                    size: 20,
                  ),
          ),
          const SizedBox(width: 12),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  song.name,
                  style: const TextStyle(
                    fontSize: 14,
                    fontWeight: FontWeight.w500,
                    color: Colors.black87,
                  ),
                ),
                const SizedBox(height: 2),
                Text(
                  song.artistsString,
                  style: TextStyle(
                    fontSize: 12,
                    color: Colors.grey[600],
                  ),
                ),
              ],
            ),
          ),
          const SizedBox(width: 8),
          Icon(
            Icons.play_circle_outline,
            color: Colors.grey[600],
            size: 20,
          ),
        ],
        ),
      ),
    );
  }

  Widget _buildNewSongItem(Song song, int index) {
    return InkWell(
      onTap: () async {
        final playerService = Provider.of<MusicPlayerService>(context, listen: false);
        await playerService.setPlaylist(_newSongs, startIndex: index - 1);
      },
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
        child: Row(
        children: [
          Container(
            width: 24,
            height: 24,
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(6),
              border: Border.all(color: Colors.black12),
            ),
            child: Center(
              child: Text(
                '$index',
                style: const TextStyle(
                  fontSize: 12,
                  fontWeight: FontWeight.bold,
                  color: Colors.black54,
                ),
              ),
            ),
          ),
          const SizedBox(width: 12),
          // 专辑图显示在歌名前
          Container(
            width: 48,
            height: 48,
            decoration: BoxDecoration(
              color: Colors.grey[300],
              borderRadius: BorderRadius.circular(6),
            ),
            child: song.albumImageUrl != null && song.albumImageUrl!.isNotEmpty
                ? ClipRRect(
                    borderRadius: BorderRadius.circular(6),
                    child: Image.network(
                      song.albumImageUrl!,
                      fit: BoxFit.cover,
                      errorBuilder: (context, error, stackTrace) => const Icon(
                        Icons.music_note,
                        color: Colors.grey,
                        size: 20,
                      ),
                    ),
                  )
                : const Icon(
                    Icons.music_note,
                    color: Colors.grey,
                    size: 20,
                  ),
          ),
          const SizedBox(width: 12),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  song.name,
                  style: const TextStyle(
                    fontSize: 14,
                    fontWeight: FontWeight.w500,
                    color: Colors.black87,
                  ),
                ),
                const SizedBox(height: 2),
                Text(
                  song.artistsString,
                  style: TextStyle(
                    fontSize: 12,
                    color: Colors.grey[600],
                  ),
                ),
              ],
            ),
          ),
          const SizedBox(width: 8),
          Icon(
            Icons.play_circle_outline,
            color: Colors.grey[600],
            size: 20,
          ),
        ],
        ),
      ),
    );
  }

  Widget _buildFavoriteItem(Song song, int index) {
    return GestureDetector(
      onTap: () async {
        final playerService = Provider.of<MusicPlayerService>(context, listen: false);
        await playerService.setPlaylist(_favoriteSongs, startIndex: index - 1);
      },
      child: Container(
        margin: const EdgeInsets.only(bottom: 8),
        padding: const EdgeInsets.all(12),
        decoration: BoxDecoration(
          color: Colors.grey[50],
          borderRadius: BorderRadius.circular(8),
        ),
        child: Row(
        children: [
          Container(
            width: 24,
            height: 24,
            decoration: BoxDecoration(
              color: Colors.grey[300],
              borderRadius: BorderRadius.circular(4),
            ),
            child: Center(
              child: Text(
                '$index',
                style: const TextStyle(
                  fontSize: 12,
                  fontWeight: FontWeight.bold,
                  color: Colors.black54,
                ),
              ),
            ),
          ),
          const SizedBox(width: 12),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  song.name,
                  style: const TextStyle(
                    fontSize: 14,
                    fontWeight: FontWeight.w500,
                    color: Colors.black87,
                  ),
                ),
                const SizedBox(height: 2),
                Text(
                  song.artistsString,
                  style: TextStyle(
                    fontSize: 12,
                    color: Colors.grey[600],
                  ),
                ),
              ],
            ),
          ),
          // 删除按钮
          IconButton(
            icon: Icon(
              Icons.delete_outline,
              size: 18,
              color: Colors.red[400],
            ),
            onPressed: () => _showDeleteFavoriteDialog(song),
            padding: const EdgeInsets.all(4),
            constraints: const BoxConstraints(
              minWidth: 32,
              minHeight: 32,
            ),
          ),
          const SizedBox(width: 4),
          Icon(
            Icons.play_circle_outline,
            color: Colors.grey[600],
            size: 20,
          ),
        ],
        ),
      ),
    );
  }

  Widget _buildHistoryItem(Song song) {
    return Container(
      margin: const EdgeInsets.only(bottom: 8),
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: Colors.grey[50],
        borderRadius: BorderRadius.circular(8),
      ),
      child: Row(
        children: [
          Container(
            width: 40,
            height: 40,
            decoration: BoxDecoration(
              color: Colors.grey[300],
              borderRadius: BorderRadius.circular(6),
            ),
            child: song.albumImageUrl != null && song.albumImageUrl!.isNotEmpty
                ? ClipRRect(
                    borderRadius: BorderRadius.circular(6),
                    child: Image.network(
                      song.albumImageUrl!,
                      fit: BoxFit.cover,
                      errorBuilder: (context, error, stackTrace) => const Icon(
                        Icons.music_note,
                        color: Colors.grey,
                        size: 20,
                      ),
                    ),
                  )
                : const Icon(
                    Icons.music_note,
                    color: Colors.grey,
                    size: 20,
                  ),
          ),
          const SizedBox(width: 12),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  song.name,
                  style: const TextStyle(
                    fontSize: 14,
                    fontWeight: FontWeight.w500,
                    color: Colors.black87,
                  ),
                ),
                const SizedBox(height: 2),
                Text(
                  song.artistsString,
                  style: TextStyle(
                    fontSize: 12,
                    color: Colors.grey[600],
                  ),
                ),
              ],
            ),
          ),
          Text(
            '',
            style: TextStyle(
              fontSize: 12,
              color: Colors.grey[600],
            ),
          ),
          const SizedBox(width: 8),
          Icon(
            Icons.play_circle_outline,
            color: Colors.grey[600],
            size: 20,
          ),
        ],
      ),
    );
  }

  Widget _buildHistoryItemWithDelete(Song song) {
    return GestureDetector(
      onTap: () async {
        final playerService = Provider.of<MusicPlayerService>(context, listen: false);
        await playerService.setPlaylist(_historySongs, startIndex: _historySongs.indexOf(song));
      },
      child: Container(
        margin: const EdgeInsets.only(bottom: 8),
        padding: const EdgeInsets.all(12),
        decoration: BoxDecoration(
          color: Colors.grey[50],
          borderRadius: BorderRadius.circular(8),
        ),
        child: Row(
          children: [
            Container(
              width: 40,
              height: 40,
              decoration: BoxDecoration(
                color: Colors.grey[300],
                borderRadius: BorderRadius.circular(6),
              ),
              child: song.albumImageUrl != null && song.albumImageUrl!.isNotEmpty
                  ? ClipRRect(
                      borderRadius: BorderRadius.circular(6),
                      child: Image.network(
                        song.albumImageUrl!,
                        fit: BoxFit.cover,
                        errorBuilder: (context, error, stackTrace) => const Icon(
                          Icons.music_note,
                          color: Colors.grey,
                          size: 20,
                        ),
                      ),
                    )
                  : const Icon(
                      Icons.music_note,
                      color: Colors.grey,
                      size: 20,
                    ),
            ),
            const SizedBox(width: 12),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    song.name,
                    style: const TextStyle(
                      fontSize: 14,
                      fontWeight: FontWeight.w500,
                      color: Colors.black87,
                    ),
                  ),
                  const SizedBox(height: 2),
                  Text(
                    song.artistsString,
                    style: TextStyle(
                      fontSize: 12,
                      color: Colors.grey[600],
                    ),
                  ),
                ],
              ),
            ),
            // 删除按钮
            IconButton(
              icon: Icon(
                Icons.delete_outline,
                size: 18,
                color: Colors.red[400],
              ),
              onPressed: () => _showDeleteHistoryDialog(song),
              padding: const EdgeInsets.all(4),
              constraints: const BoxConstraints(
                minWidth: 32,
                minHeight: 32,
              ),
            ),
            const SizedBox(width: 4),
            Icon(
              Icons.play_circle_outline,
              color: Colors.grey[600],
              size: 20,
            ),
          ],
        ),
      ),
    );
  }

  void _showDeleteFavoriteDialog(Song song) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('确认删除'),
          content: Text('确定要从收藏夹中删除 "${song.name}" 吗？'),
          actions: [
            TextButton(
              onPressed: () {
                Navigator.of(context).pop();
              },
              child: const Text('取消'),
            ),
            TextButton(
              onPressed: () {
                Navigator.of(context).pop();
                _deleteFavorite(song);
              },
              child: const Text('删除'),
            ),
          ],
        );
      },
    );
  }

  void _showDeleteHistoryDialog(Song song) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('确认删除'),
          content: Text('确定要从播放历史中删除 "${song.name}" 吗？'),
          actions: [
            TextButton(
              onPressed: () {
                Navigator.of(context).pop();
              },
              child: const Text('取消'),
            ),
            TextButton(
              onPressed: () {
                Navigator.of(context).pop();
                _deleteHistoryItem(song);
              },
              child: const Text('删除'),
            ),
          ],
        );
      },
    );
  }

  void _deleteFavorite(Song song) async {
    try {
      await FavoritesService.removeFromFavorites(song);
      _loadFavorites(); // 重新加载收藏夹
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('已从收藏夹中删除 "${song.name}"'),
            duration: const Duration(seconds: 2),
          ),
        );
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('删除失败: $e'),
            backgroundColor: Theme.of(context).colorScheme.error,
            duration: const Duration(seconds: 2),
          ),
        );
      }
    }
  }

  void _deleteHistoryItem(Song song) async {
    try {
      await HistoryService.removeFromHistory(song);
      _loadHistory(); // 重新加载历史记录
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('已从播放历史中删除 "${song.name}"'),
            duration: const Duration(seconds: 2),
          ),
        );
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('删除失败: $e'),
            backgroundColor: Theme.of(context).colorScheme.error,
            duration: const Duration(seconds: 2),
          ),
        );
      }
    }
  }

  Future<void> _clearAllHistory() async {
    final confirmed = await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('清空播放历史'),
        content: const Text('确定要清空所有播放历史吗？此操作无法撤销。'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context, false),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () => Navigator.pop(context, true),
            style: TextButton.styleFrom(
              foregroundColor: Colors.red,
            ),
            child: const Text('确定'),
          ),
        ],
      ),
    );

    if (confirmed == true) {
      try {
        await HistoryService.clearHistory();
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(
              content: Text('播放历史已清空'),
              duration: Duration(seconds: 2),
            ),
          );
        }
      } catch (e) {
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: Text('清空失败: $e'),
              backgroundColor: Theme.of(context).colorScheme.error,
              duration: const Duration(seconds: 2),
            ),
          );
        }
      }
    }
  }

  String _formatDuration(int durationInSeconds) {
    final minutes = durationInSeconds ~/ 60;
    final seconds = durationInSeconds % 60;
    return '${minutes.toString().padLeft(2, '0')}:${seconds.toString().padLeft(2, '0')}';
  }

}
